package com.goldplusgold.tradedelay.app.trade.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.base.constant.ErrorCodeConstant;
import com.goldplusgold.tradedelay.app.my.networkservice.ApiConfig;
import com.goldplusgold.tradedelay.app.trade.activity.MyAssetsActivity;
import com.goldplusgold.tradedelay.app.trade.activity.TradeWebViewActivity;
import com.goldplusgold.tradedelay.app.trade.activity.TriggerListActivity;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.Customer;
import com.goldplusgold.tradedelay.app.base.utils.ActivityUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2017/5/19.
 */

public class TradeAccountFragment extends BaseFragment implements Handler.Callback {

    @BindView(R.id.iv_head_image)
    ImageView ivHeadImage;
    @BindView(R.id.rl_my_info)
    RelativeLayout rlMyInfo;
    @BindView(R.id.id_text_view_bank_id)
    TextView mTextVewBankId;
    @BindView(R.id.id_text_view_trade_no)
    TextView mTextVewTradeNo;
    private Handler handler = new Handler(this);
    public static final String FROM_PAGE_NAME = "trade_account_page";

    public static TradeAccountFragment newInstance() {

        Bundle args = new Bundle();
        TradeAccountFragment fragment = new TradeAccountFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.drawer_trade_right;
    }


    @OnClick({R.id.id_left_view, R.id.rl_asset, R.id.rl_trans_account, R.id.rl_stop_loss, R.id.rl_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_left_view:
                FragmentManager fm = getActivity().getSupportFragmentManager();
                fm.popBackStack();
                break;
            case R.id.rl_asset:
                actionMyAssetsPage();
                break;
            case R.id.rl_trans_account:
                actionBrowserPage(ApiConfig._CASH_OPERATION_URL);
                break;
            case R.id.rl_stop_loss:
                Intent intent = new Intent(getContext(), TriggerListActivity.class);
                intent.putExtra("fromPage", FROM_PAGE_NAME);
                startActivity(intent);
                break;
            case R.id.rl_setting:
                actionBrowserPage(ApiConfig._TD_SETTING_URL);
                break;
        }

    }

    private void actionBrowserPage(String url) {
        Intent intent = new Intent(getActivity(), TradeWebViewActivity.class);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        new LoadCustomerAsyncTask().execute(AsyncTask.TYPE_NET);
    }

    private void actionMyAssetsPage() {
        Intent intent = new Intent(getActivity(), MyAssetsActivity.class);
        startActivity(intent);
    }

    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {

            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE:
                String message = (String) msg.obj;
                ActivityUtils.forceQuit(getActivity(), message);
                break;
        }
        return true;
    }


    public class LoadCustomerAsyncTask extends AsyncTask<Void, Void, Customer> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected Customer doInBackground(Void... params) {

            try {
                Customer customer = TradeService.getInstance().getCustomer();
                Log.d("customer", customer.toString());
                return customer;
            } catch (ServerException e) {
                if (ErrorCodeConstant._EXTRUSION_SIGN_IN_CODE.equals(e.returnCode)) {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_EXTRUDE_LOGIN_CODE, e.getMessage());
                } else {
                    sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Customer customer) {
            super.onPostExecute(customer);
            if (!isAvailableActivity()) {
                return;
            }
            dismisLoadingControl();
            if (customer == null) {
                return;
            }
            mTextVewTradeNo.setText(customer.getAcctNo());
            mTextVewBankId.setText(customer.getBankName() + " 尾号" + customer.getBankCard());
        }
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        finishActivity();
    }

}
